import type { App } from 'vue'
import { createI18n } from 'vue-i18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import type { I18n, I18nOptions } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { setHtmlPageLang } from './helper'

export let i18n: ReturnType<typeof createI18n>
const createI18nOptions = async (): Promise<I18nOptions> => {
  const localeStore = useLocaleStoreWithOut()
  const { currentLocale, localeMap } = storeToRefs(localeStore)
  const defaultLocal = await import(`./locales/${currentLocale.value.lang}.ts`)
  const message = defaultLocal.default ?? {}

  setHtmlPageLang(currentLocale.value.lang)

  localeStore.setCurrentLocale({ lang: currentLocale.value.lang })

  return {
    legacy: false,
    locale: currentLocale.value.lang,
    fallbackLocale: currentLocale.value.lang,
    messages: {
      [currentLocale.value.lang]: message
    },
    availableLocales: localeMap.value.map(v => v.lang),
    sync: true,
    silentTranslationWarn: true,
    missingWarn: false,
    silentFallbackWarn: true
  }
}

export const setupI18n = async (app: App<Element>) => {
  const options = await createI18nOptions()
  i18n = createI18n(options) as I18n
  app.use(i18n)
}
